package com.zzyl.nursing.service.impl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.dto.IotMsgNotifyData;
import com.zzyl.nursing.dto.IotMsgService;
import com.zzyl.nursing.dto.PageDeviceDataList;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.service.IDeviceDataService;
import com.zzyl.nursing.service.IDeviceService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 设备数据表Service业务层处理
 *
 * @author mr.luo
 * @date 2025-05-25
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService {
    @Autowired
    private DeviceDataMapper deviceDataMapper;
    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 查询设备数据表
     *
     * @param id 设备数据表主键
     * @return 设备数据表
     */
    @Override
    public DeviceData selectDeviceDataById(Long id) {
        return getById(id);
    }

    /**
     * 查询设备数据表列表
     *
     * @param deviceData 设备数据表
     * @return 设备数据表
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceData deviceData) {
        return deviceDataMapper.selectDeviceDataList(deviceData);
    }

    /**
     * 新增设备数据表
     *
     * @param deviceData 设备数据表
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData) {
        return save(deviceData) ? 1 : 0;
    }

    /**
     * 修改设备数据表
     *
     * @param deviceData 设备数据表
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData) {
        return updateById(deviceData) ? 1 : 0;
    }

    /**
     * 批量删除设备数据表
     *
     * @param ids 需要删除的设备数据表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备数据表信息
     *
     * @param id 设备数据表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id) {
        return removeById(id) ? 1 : 0;
    }


    /**
     * 基于IOT上传保存到deviceData表中
     * 将最新的数据使用redisTemplate hash存储到redis中  新数据会覆盖旧数据
     *
     * @param message
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveBachedDeviceData(String message) {
        //首先要获取到信息里面的数据
        if (message == null) {
            throw new BaseException("未获取到信息");
        }
        //从里面提取信息
        JSONObject jsonObject = JSONUtil.parseObj(message);
        IotMsgNotifyData iotMsgNotifyData = jsonObject.get("notify_data", IotMsgNotifyData.class);
        //判断是否获取到iotMsgNotifyData
        if (iotMsgNotifyData == null) {
            throw new BaseException("未获取到信息");
        }
        if (iotMsgNotifyData.getHeader() == null || iotMsgNotifyData.getBody() == null) {
            throw new BaseException("该设备不存在");
        }
        //首先先判断设备是否存在 获取设备物联网设备id
        String deviceId = iotMsgNotifyData.getHeader().getDeviceId();
        //到device表中查询，该设备是否存在
        Device device = deviceService.lambdaQuery().eq(Device::getIotId, deviceId).one();
        if (device == null) {
            throw new BaseException("该设备不存在");
        }
        //存在，取出数据对数据封装，然后保存到数据库中
        List<IotMsgService> services = iotMsgNotifyData.getBody().getServices();
        //由于可能存在多台设备数据所以需要创建一个集合，一块插入
        List<DeviceData> deviceDataList = new ArrayList<>();
        //开始遍历集合保存数据
        services.forEach(s -> {
            //先对上报时间数据进行解析
            try {
                String eventTimeStr = s.getEventTime();
                LocalDateTime eventTime = OffsetDateTime.parse(eventTimeStr, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssX")).atZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();
                Map<String, Object> properties = s.getProperties();
                properties.forEach((k, v) -> {
                    DeviceData deviceData = new DeviceData();
                    BeanUtils.copyProperties(device, deviceData);
                    deviceData.setId(null);
                    deviceData.setFunctionId(k);
                    deviceData.setAccessLocation(device.getBindingLocation());
                    deviceData.setDataValue(String.valueOf(v));
                    deviceData.setAlarmTime(eventTime);
                    deviceDataList.add(deviceData);
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        try {
            if (!CollectionUtils.isEmpty(deviceDataList)) {
                boolean b = this.saveBatch(deviceDataList);
                System.out.println(b);
                redisTemplate.opsForHash().put(CacheConstants.DEVICE_LAST_DATA_KEY,
                        deviceId, JSONUtil.toJsonStr(deviceDataList));
                if (!b) {
                    throw new BaseException("保存失败");
                }
            }
        } catch (BaseException e) {
           e.printStackTrace();
        }
    }


    /**
     * 2.1 获取设备数据分页结果
     *
     * @param pageList
     */
    @Override
    public Page<DeviceData> pageQuery(PageDeviceDataList pageList) {
        Page<DeviceData> page = new Page<>(pageList.getPageNum(), pageList.getPageSize());
        lambdaQuery().like(pageList.getDeviceName() != null, DeviceData::getDeviceName, pageList.getDeviceName())
                .eq(pageList.getFunctionId() != null, DeviceData::getFunctionId, pageList.getFunctionId())
                .between(pageList.getEndTime() != null && pageList.getStartTime() != null, DeviceData::getAlarmTime, pageList.getStartTime(), pageList.getEndTime())
                .page(page);
        return page;
    }
}
